package logic

import (
	"context"
	"elm_srv/cache"
	"fmt"
	"strconv"

	"elm_srv/elm"
	"elm_srv/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type StatsCartLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewStatsCartLogic(ctx context.Context, svcCtx *svc.ServiceContext) *StatsCartLogic {
	return &StatsCartLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *StatsCartLogic) StatsCart(in *elm.StatsCartRequest) (*elm.StatsCartResponse, error) {
	// todo: add your logic here and delete this line

	key := fmt.Sprintf("cart_%d_*", in.UserId)
	keys := cache.Rdb.Keys(context.Background(), key).Val()

	var total int64
	var sumPrice float64

	if len(keys) == 0 {
		return &elm.StatsCartResponse{}, nil
	}

	for _, s := range keys {
		goodsMap, _ := cache.Rdb.HGetAll(context.Background(), s).Result()

		goodsPrice, _ := strconv.ParseFloat(goodsMap["goods_price"], 64)
		num, _ := strconv.Atoi(goodsMap["num"])

		total += 1
		sumPrice += goodsPrice * float64(num)
	}

	return &elm.StatsCartResponse{
		Total:    total,
		SumPrice: float32(sumPrice),
	}, nil
}
